package com.study.nacos.nacosstudy.exception;

import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Description :
 * @Version : V1.0.0
 * @Date : 2022/8/1 19:56
 */
@Component
public class MyBlockExceptionHandler  {
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws Exception {
        System.out.println("BlockExceptionHandler BlockException================" + e.getRule());
        String error = "";
        if (e instanceof FlowException) {
            error = "接口被限流了";
        } else if (e instanceof DegradeException) {
            error = "服务降级了";
//        } else if (e instanceof ParamFlowException) {
//            error = "热点参数限流了";
//        } else if (e instanceof AuthorityException) {
            error = "授权规则不通过";
        }

        //返回Json数据
        httpServletResponse.setStatus(500);
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType(MediaType.APPLICATION_JSON_VALUE);
        PrintWriter writer = null;
        try {
            writer = httpServletResponse.getWriter();
            writer.write(error);
            writer.flush();
        } catch (IOException ioException) {
            System.out.println("异常:" + ioException.getMessage());
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
    }
}
